<template>
  <lay-loading :loading="loading2" tip="加载中...">
    <div style="padding: 5px; margin: 0; background-color: #fff; border-radius: 0px;">
      <!-- <span style="float: left;">筛选：</span> -->
      <lay-form :model="filter" isLabelTooltip>
        <!-- <lay-form-item prop="province" mode="inline" size="xs" style="margin-bottom: 0;">
          <lay-select v-model="filter.province" multiple allow-clear minCollapsedNum=1 placeholder="省" size="xs">
            <lay-select-option value="1" label="广西"></lay-select-option>
          </lay-select>
        </lay-form-item> -->
        <lay-form-item prop="city" mode="inline" size="xs" style="margin-bottom: 0;">
          <lay-select v-model="filter.city" multiple showSearch allow-clear minCollapsedNum=1 placeholder="市" size="xs">
            <lay-select-option v-for="city in filterCity" :key="city" :value="city" :label="city"></lay-select-option>
          </lay-select>
        </lay-form-item>
        <lay-form-item prop="county" mode="inline" size="xs" style="margin-bottom: 0;">
          <lay-select v-model="filter.county" multiple showSearch allow-clear minCollapsedNum=1 placeholder="区/县"
            size="xs">
            <lay-select-option v-for="county in filterCounty" :key="county" :value="county"
              :label="county"></lay-select-option>
          </lay-select>
        </lay-form-item>
        <lay-form-item prop="town" mode="inline" size="xs" style="margin-bottom: 0;">
          <lay-select v-model="filter.town" multiple showSearch allow-clear minCollapsedNum=1 placeholder="乡/镇"
            size="xs">
            <lay-select-option v-for="town in filterTown" :key="town" :value="town" :label="town"></lay-select-option>
          </lay-select>
        </lay-form-item>

        <lay-form-item prop="town" mode="inline" size="xs" style="margin-bottom: 0;">
          <lay-select v-model="filter.forestClass" multiple showSearch allow-clear minCollapsedNum=1 placeholder="森林类别"
            size="xs">
            <lay-select-option v-for="value in forestClassList" :key="value.id" :value="value.name"
              :label="value.level ? value.name + '(' + value.level + ')' : value.name"></lay-select-option>
          </lay-select>
        </lay-form-item>
        <lay-form-item prop="town" mode="inline" size="xs" style="margin-bottom: 0;">
          <lay-select v-model="filter.ecologicalZone" multiple showSearch allow-clear minCollapsedNum=1
            placeholder="生态分区" size="xs">
            <lay-select-option v-for="value in ecologicalZoneList" :key="value.id" :value="value.name"
              :label="value.name"></lay-select-option>
          </lay-select>
        </lay-form-item>

      </lay-form>
    </div>

    <lay-table :page="page" :resize="true" :height="tableHeight" :columns="columns" :loading="loading"
      @row-double="edit" :default-toolbar="defaultToolbars" :data-source="dataSource"
      v-model:selected-keys="selectedKeys" @change="change" @sortChange="sortChange" even>
      <!-- <template #status="{ row }">
        <lay-switch :model-value="row.status" @change="changeStatus($event, row)"></lay-switch>
      </template> -->
      <template v-slot:toolbar>
        <lay-button size="xs" type="primary" @click="add">
          <lay-icon type="layui-icon-addition"></lay-icon> 新增
        </lay-button>
        <lay-popconfirm content="确定要删除所选数据吗？确认后将无法恢复！" trigger="click" position="bottom" @confirm="remove"
          @cancel="() => layer.msg('操作已取消！', { icon: 3, time: 1000 })">
          <lay-button size="xs" border="red" border-style="dashed">删除</lay-button>
        </lay-popconfirm>
      </template>
      <template v-slot:operator="{ row }">
        <lay-button size="xs" @click="edit(row)" type="primary">编辑</lay-button>
        <lay-button size="xs" title="查看">查看</lay-button>
      </template>
    </lay-table>
  </lay-loading>

  <!-- 新增 ========================================== -->
  <lay-layer v-model="addVisible" :shade="false" :area="['65%', '']" :resize="true" :title="'新增资源'" :btn="addAction">
    <div style="padding: 10px;">
      <lay-scroll height="60vh" thumbColor="#999">
        <lay-form :model="newResource" ref="addResourceForm" isLabelTooltip style="padding: 10px;">
          <lay-form-item label="省" prop="province" required mode="inline">
            <lay-input v-model="newResource.province"></lay-input>
          </lay-form-item>
          <lay-form-item label="市" prop="city" required mode="inline">
            <lay-input v-model="newResource.city"></lay-input>
          </lay-form-item>
          <lay-form-item label="县、区" prop="county" required mode="inline">
            <lay-input v-model="newResource.county"></lay-input>
          </lay-form-item>
          <lay-form-item label="乡、镇" prop="town" mode="inline">
            <lay-input v-model="newResource.town"></lay-input>
          </lay-form-item>
          <lay-form-item label="村" prop="village" mode="inline">
            <lay-input v-model="newResource.village"></lay-input>
          </lay-form-item>
          <div></div>
          <lay-form-item label="植被生态区" prop="vegetation_ecological_zone" required mode="inline">
            <!-- <lay-input v-model="newResource.vegetation_ecological_zone"></lay-input> -->
            <lay-select v-model="newResource.vegetation_ecological_zone" placeholder="请选择">
              <lay-select-option v-for="item in vegetationEcologicalZoneList" :key="item.id" :value="item.id"
                :label="item.name"></lay-select-option>
            </lay-select>

          </lay-form-item>
          <lay-form-item label="生态工程区" prop="ecological_engineering_zone" required mode="inline">
            <!-- <lay-input v-model="newResource.ecological_engineering_zone"></lay-input> -->
            <lay-select v-model="newResource.ecological_engineering_zone" placeholder="请选择">
              <lay-select-option v-for="item in ecologicalEngineeringZoneList" :key="item.id" :value="item.id"
                :label="item.name"></lay-select-option>
            </lay-select>
          </lay-form-item>

          <lay-form-item label="森林类别" prop="forest_class" required mode="inline">
            <!-- <lay-input v-model="newResource.forest_class"></lay-input> -->
            <lay-select v-model="newResource.forest_class" placeholder="请选择">
              <lay-select-option v-for="item in forestClassList" :key="item.id" :value="item.id"
                :label="item.level ? item.name + '(' + item.level + ')' : item.name"></lay-select-option>
            </lay-select>

          </lay-form-item>
          <lay-form-item label="生态分区" prop="ecological_zone" required mode="inline">
            <!-- <lay-input v-model="newResource.ecological_zone"></lay-input> -->
            <lay-select v-model="newResource.ecological_zone" placeholder="请选择">
              <lay-select-option v-for="item in ecologicalZoneList" :key="item.id" :value="item.id"
                :label="item.name"></lay-select-option>
            </lay-select>
          </lay-form-item>
          <lay-form-item label="生态分区2" prop="ecological_zone_2" required mode="inline">
            <!-- <lay-input :disabled="true" v-model="newResource.ecological_zone_2"></lay-input> -->

            <lay-select v-model="newResource.ecological_zone_2" :disabled="true">
              <lay-select-option :value="newResource.ecological_zone_2"
                :label="newResource.ecological_zone_2"></lay-select-option>
            </lay-select>

          </lay-form-item>
          <lay-form-item label="优势树种" prop="dominant_tree_species" required mode="inline">
            <!-- <lay-input v-model="newResource.dominant_tree_species"></lay-input> -->
            <lay-select v-model="newResource.dominant_tree_species" placeholder="请选择">
              <lay-select-option v-for="item in treeSpeciesList" :key="item.id" :value="item.id"
                :label="item.name"></lay-select-option>
            </lay-select>
          </lay-form-item>
          <lay-form-item label="起源" prop="origin" required mode="inline">
            <!-- <lay-input v-model="newResource.origin"></lay-input> -->
            <lay-select v-model="newResource.origin" placeholder="请选择">
              <lay-select-option v-for="item in originList" :key="item.id" :value="item.id"
                :label="item.name"></lay-select-option>
            </lay-select>
          </lay-form-item>
          <lay-form-item label="年龄组" prop="age_group" required mode="inline">
            <!-- <lay-input v-model="newResource.age_group"></lay-input> -->
            <lay-select v-model="newResource.age_group" placeholder="请选择">
              <lay-select-option v-for="item in ageGroupList" :key="item.id" :value="item.id"
                :label="item.name"></lay-select-option>
            </lay-select>
          </lay-form-item>
          <div></div>
          <lay-form-item label="面积(公顷)" prop="area" mode="inline">
            <lay-input v-model="newResource.area"></lay-input>
          </lay-form-item>
          <lay-form-item label="蓄积" prop="stock" mode="inline">
            <lay-input v-model="newResource.stock"></lay-input>
          </lay-form-item>
          <lay-form-item label="每公顷蓄积" prop="stock_per_ha" mode="inline">
            <lay-input v-model="newResource.stock_per_ha"></lay-input>
          </lay-form-item>
          <lay-form-item label="平均树高" prop="mean_tree_height" mode="inline">
            <lay-input v-model="newResource.mean_tree_height"></lay-input>
          </lay-form-item>
          <lay-form-item label="平均胸径" prop="mean_dbh" mode="inline">
            <lay-input v-model="newResource.mean_dbh"></lay-input>
          </lay-form-item>
          <lay-form-item label="林分生物量" prop="forest_stand_biomass" mode="inline">
            <lay-input v-model="newResource.forest_stand_biomass"></lay-input>
          </lay-form-item>
          <lay-form-item label="系数" prop="coefficient" mode="inline">
            <lay-input v-model="newResource.coefficient"></lay-input>
          </lay-form-item>
          <lay-form-item label="备注" prop="remark" mode="inline">
            <lay-input v-model="newResource.remark"></lay-input>
          </lay-form-item>

        </lay-form>
      </lay-scroll>
    </div>
  </lay-layer>

  <!-- 编辑 ========================================== -->
  <lay-layer v-model="editVisible" :shade="false" :area="['65%', '']" :resize="true" :title="'编辑资源'" :btn="editAction">
    <div style="padding: 10px;">
      <lay-scroll height="60vh" thumbColor="#999">
        <lay-form :model="editResource" ref="editResourceForm" isLabelTooltip style="padding: 10px;">
          <lay-form-item label="ID" prop="id" mode="inline" required>
            <lay-input v-model="editResource.id" :disabled="true"></lay-input>
          </lay-form-item>
          <lay-form-item label="省" prop="province" required mode="inline">
            <lay-input v-model="editResource.province"></lay-input>
          </lay-form-item>
          <lay-form-item label="市" prop="city" required mode="inline">
            <lay-input v-model="editResource.city"></lay-input>
          </lay-form-item>
          <lay-form-item label="县、区" prop="county" required mode="inline">
            <lay-input v-model="editResource.county"></lay-input>
          </lay-form-item>
          <lay-form-item label="乡、镇" prop="town" mode="inline">
            <lay-input v-model="editResource.town"></lay-input>
          </lay-form-item>
          <lay-form-item label="村" prop="village" mode="inline">
            <lay-input v-model="editResource.village"></lay-input>
          </lay-form-item>
          <div></div>
          <lay-form-item label="植被生态区" prop="vegetation_ecological_zone" required mode="inline">
            <!-- <lay-input v-model="editResource.vegetation_ecological_zone"></lay-input> -->
            <lay-select v-model="editResource.vegetation_ecological_zone" placeholder="请选择">
              <lay-select-option v-for="item in vegetationEcologicalZoneList" :key="item.id" :value="item.id"
                :label="item.name"></lay-select-option>
            </lay-select>

          </lay-form-item>
          <lay-form-item label="生态工程区" prop="ecological_engineering_zone" required mode="inline">
            <!-- <lay-input v-model="editResource.ecological_engineering_zone"></lay-input> -->
            <lay-select v-model="editResource.ecological_engineering_zone" placeholder="请选择">
              <lay-select-option v-for="item in ecologicalEngineeringZoneList" :key="item.id" :value="item.id"
                :label="item.name"></lay-select-option>
            </lay-select>
          </lay-form-item>
          <lay-form-item label="森林类别" prop="forest_class" required mode="inline">
            <!-- <lay-input v-model="editResource.forest_class"></lay-input> -->
            <lay-select v-model="editResource.forest_class" placeholder="请选择">
              <lay-select-option v-for="item in forestClassList" :key="item.id" :value="item.id"
                :label="item.level ? item.name + '(' + item.level + ')' : item.name"></lay-select-option>
            </lay-select>

          </lay-form-item>
          <lay-form-item label="生态分区" prop="ecological_zone" required mode="inline">
            <!-- <lay-input v-model="editResource.ecological_zone"></lay-input> -->
            <lay-select v-model="editResource.ecological_zone" placeholder="请选择">
              <lay-select-option v-for="item in ecologicalZoneList" :key="item.id" :value="item.id"
                :label="item.name"></lay-select-option>
            </lay-select>
          </lay-form-item>
          <lay-form-item label="生态分区2" prop="ecological_zone_2" required mode="inline">
            <!-- <lay-input :disabled="true" v-model="editResource.ecological_zone_2"></lay-input> -->

            <lay-select v-model="editResource.ecological_zone_2" :disabled="true">
              <lay-select-option :value="editResource.ecological_zone_2"
                :label="editResource.ecological_zone_2"></lay-select-option>
            </lay-select>

          </lay-form-item>
          <lay-form-item label="优势树种" prop="dominant_tree_species" required mode="inline">
            <!-- <lay-input v-model="editResource.dominant_tree_species"></lay-input> -->
            <lay-select v-model="editResource.dominant_tree_species" placeholder="请选择">
              <lay-select-option v-for="item in treeSpeciesList" :key="item.id" :value="item.id"
                :label="item.name"></lay-select-option>
            </lay-select>
          </lay-form-item>
          <lay-form-item label="起源" prop="origin" required mode="inline">
            <!-- <lay-input v-model="editResource.origin"></lay-input> -->
            <lay-select v-model="editResource.origin" placeholder="请选择">
              <lay-select-option v-for="item in originList" :key="item.id" :value="item.id"
                :label="item.name"></lay-select-option>
            </lay-select>
          </lay-form-item>
          <lay-form-item label="年龄组" prop="age_group" required mode="inline">
            <!-- <lay-input v-model="editResource.age_group"></lay-input> -->
            <lay-select v-model="editResource.age_group" placeholder="请选择">
              <lay-select-option v-for="item in ageGroupList" :key="item.id" :value="item.id"
                :label="item.name"></lay-select-option>
            </lay-select>
          </lay-form-item>
          <div></div>
          <lay-form-item label="面积(公顷)" prop="area" mode="inline">
            <lay-input v-model="editResource.area"></lay-input>
          </lay-form-item>
          <lay-form-item label="蓄积" prop="stock" mode="inline">
            <lay-input v-model="editResource.stock"></lay-input>
          </lay-form-item>
          <lay-form-item label="每公顷蓄积" prop="stock_per_ha" mode="inline">
            <lay-input v-model="editResource.stock_per_ha"></lay-input>
          </lay-form-item>
          <lay-form-item label="平均树高" prop="mean_tree_height" mode="inline">
            <lay-input v-model="editResource.mean_tree_height"></lay-input>
          </lay-form-item>
          <lay-form-item label="平均胸径" prop="mean_dbh" mode="inline">
            <lay-input v-model="editResource.mean_dbh"></lay-input>
          </lay-form-item>
          <lay-form-item label="林分生物量" prop="forest_stand_biomass" mode="inline">
            <lay-input v-model="editResource.forest_stand_biomass"></lay-input>
          </lay-form-item>
          <lay-form-item label="系数" prop="coefficient" mode="inline">
            <lay-input v-model="editResource.coefficient"></lay-input>
          </lay-form-item>
          <lay-form-item label="备注" prop="remark" mode="inline">
            <lay-input v-model="editResource.remark"></lay-input>
          </lay-form-item>

        </lay-form>
      </lay-scroll>
    </div>
  </lay-layer>
</template>

<script setup>
import { ref, toRefs, watch, reactive, onMounted, h, computed } from 'vue';
import { layer } from '@layui/layui-vue';
import api from '@/api';
import ImpportResource from '@/views/resource/components/ImpportResource.vue';

const loading = ref(true);
const loading2 = ref(false);
const selectedKeys = ref([]);

const resourceList = ref([])
const dataSource = ref([]);
const page = reactive({ current: 1, limit: 20, limits: [20, 50, 100, 500], total: resourceList.value.length, layout: ["page", "limits", "prev", "refresh", "count", "next", "skip",] });

// 计算表格高度
const tableHeight = computed(() => {
  return window.innerHeight - 115 + 'px'
})

const addVisible = ref(false);
// 下拉选择列表
const vegetationEcologicalZoneList = ref([]);
const ecologicalEngineeringZoneList = ref([]);
const forestClassList = ref([]);
const ecologicalZoneList = ref([]);
const treeSpeciesList = ref([]);
const originList = ref([]);
const ageGroupList = ref([]);
const filter = reactive({
  province: ["广西"],
  city: [],
  county: [],
  town: [],
  village: [],
  forestClass: [],
  ecologicalZone: []
})
const filterCity = ref([]);
const filterCounty = ref([]);
const filterTown = ref([]);
const filterVillage = ref([]);

const getList = async () => {
  vegetationEcologicalZoneList.value = (await api.get('field/vegetationecologicalzone/list')).data.filter(item => item.status);
  ecologicalEngineeringZoneList.value = (await api.get('field/ecologicalengineeringzone/list')).data.filter(item => item.status);
  forestClassList.value = (await api.get('field/forestclass/list')).data.filter(item => item.status);
  ecologicalZoneList.value = (await api.get('field/ecologicalzone/list')).data.filter(item => item.status);
  treeSpeciesList.value = (await api.get('field/treespecies/list')).data.filter(item => item.status);
  originList.value = (await api.get('field/origin/list')).data.filter(item => item.status);
  ageGroupList.value = (await api.get('field/agegroup/list')).data.filter(item => item.status);
}
const addResourceForm = ref();

// 新增资源
async function add() {
  getList();
  addVisible.value = !addVisible.value;
}

const newResource = reactive({
  province: "广西",
})

const addResourceHandler = async () => {
  let response = await api.get('resource/add', { ...newResource });

  if (response.code === 200) {
    layer.msg(response.msg, { icon: 1, time: 1000 });
    getResourceList(); // 刷新用户列表
    addVisible.value = !addVisible.value;
  } else {
    layer.msg(response.msg, { icon: 2, time: 2000 });
  }
}

const addAction = ref([
  {
    text: "新增",
    callback: () => {
      if (addResourceForm.value.validate()) {
        addResourceHandler();
      } else {
        layer.msg("请填写完整信息！", { icon: 2, time: 2000 });
        return;
      }
    }
  },
  {
    text: "取消",
    callback: () => {
      layer.msg("操作已取消！", { icon: 3, time: 1500 });
      addVisible.value = !addVisible.value;
    }
  }
])

const editVisible = ref(false);
const editResourceForm = ref();

// 编辑资源
const editResource = reactive({
  province: "广西",
})

function edit(row) {
  editResource.id = row.id;
  editResource.city = row.city;
  editResource.county = row.county;
  editResource.town = row.town;
  editResource.village = row.village;
  editResource.vegetation_ecological_zone = vegetationEcologicalZoneList.value.find(item => item.name === row.vegetation_ecological_zone).id;
  editResource.ecological_engineering_zone = ecologicalEngineeringZoneList.value.find(item => item.name === row.ecological_engineering_zone).id;
  editResource.forest_class = forestClassList.value.find(item => item.name === row.forest_class && item.level === row.forest_level).id;
  editResource.ecological_zone = ecologicalZoneList.value.find(item => item.name === row.ecological_zone).id;
  editResource.ecological_zone_2 = row.ecological_zone_2;
  editResource.dominant_tree_species = treeSpeciesList.value.find(item => item.name === row.dominant_tree_species).id;
  editResource.origin = originList.value.find(item => item.name === row.origin).id;
  editResource.age_group = ageGroupList.value.find(item => item.name === row.age_group).id;
  editResource.area = row.area;
  editResource.stock = row.stock;
  editResource.stock_per_ha = row.stock_per_ha;
  editResource.mean_tree_height = row.mean_tree_height;
  editResource.mean_dbh = row.mean_dbh;
  editResource.forest_stand_biomass = row.forest_stand_biomass;
  editResource.coefficient = row.coefficient;
  editResource.remark = row.remark;

  editVisible.value = !editVisible.value;
}


const editResourceHandler = async () => {
  let response = await api.get('resource/update', { ...editResource });

  if (response.code === 200) {
    layer.msg(response.msg, { icon: 1, time: 1000 });
    getResourceList(); // 刷新用户列表
    editVisible.value = !editVisible.value;
  } else {
    layer.msg(response.msg, { icon: 2, time: 2000 });
  }
}


const editAction = ref([
  {
    text: "保存",
    callback: () => {
      if (editResourceForm.value.validate()) {
        editResourceHandler();
      } else {
        layer.msg("请填写完整信息！", { icon: 2, time: 2000 });
        return;
      }
    }
  },
  {
    text: "取消",
    callback: () => {
      layer.msg("操作已取消！", { icon: 3, time: 1500 });
      editVisible.value = !editVisible.value;
    }
  }
])

const columns = ref([
  { title: "选项", type: "checkbox", fixed: "left", width: '10px' },
  { title: "ID", key: "id", fixed: "left", align: 'center', width: '20px', hide: true, },
  { title: "年度", key: "year", fixed: "left", align: 'center', hide: true, width: '10px', },
  { title: "省", key: "province", align: 'center', hide: true, ellipsisTooltip: true, },
  { title: "市", key: "city", align: 'center', ellipsisTooltip: true },
  { title: "区/县", key: "county", align: 'center', hide: false, ellipsisTooltip: true, },
  { title: "乡/镇", key: "town", align: 'center', hide: true, ellipsisTooltip: true, },
  { title: "村", key: "village", align: 'center', hide: true, ellipsisTooltip: true, },
  { title: "植被生态区", key: "vegetation_ecological_zone", align: 'center', ellipsisTooltip: true, },
  { title: "生态工程区", key: "ecological_engineering_zone", align: 'center', ellipsisTooltip: true, },
  { title: "生态分区", key: "ecological_zone", align: 'center' },
  { title: "森林类别", key: "forest_class", align: 'center' },
  { title: "事权级", key: "forest_level", align: 'center' },
  { title: "生态分区2", key: "ecological_zone_2", align: 'center', hide: true, ellipsisTooltip: true, },
  { title: "优势树种", key: "dominant_tree_species", align: 'center', ellipsisTooltip: true, },
  { title: "起源", key: "origin", align: 'center' },
  { title: "年龄组", key: "age_group", align: 'center' },
  { title: "面积(ha)", key: "area", align: 'center', },
  { title: "蓄积(m³)", key: "stock", align: 'center', },
  { title: "蓄积(m³/ha)", key: "stock_per_ha", align: 'center' },
  { title: "平均树高(m)", key: "mean_tree_height", align: 'center' },
  { title: "平均胸径(cm)", key: "mean_dbh", align: 'center' },
  { title: "林分生物量", key: "forest_stand_biomass", align: 'center', },
  { title: "系数", key: "coefficient", align: 'center' },
  { title: "备注", key: "remark", ellipsisTooltip: true, hide: true, },
  { title: "操作", width: "100px", align: 'center', customSlot: "operator", key: "operator", fixed: "right", ignoreExport: true }
]);

const defaultToolbars = [
  "filter",
  {
    icon: "layui-icon-add-one",
    title: "导入",
    onClick: () => {
      layer.drawer({
        title: "批量导入数据",
        content: h(ImpportResource),
        area: ['100%', ''],
        offset: "t",
        resize: true,
        close: () => {
          loading.value = true
          getResourceList().then(() => {
            loading.value = false
          })
        }
      })
      console.log("导入数据")
    }
  },
  {
    icon: "layui-icon-refresh",
    title: "刷新",
    onClick: () => {
      loading.value = true;
      getResourceList();
    }
  },
  "export",
  // "print",
]

const sortChange = (key, sort) => {
  layer.msg(`字段${key} - 排序${sort}, 你可以利用 sort-change 实现服务端排序`)
}

// 获取资源列表
async function getResourceList() {
  try {
    const response = await api.get('resource/list');
    if (response.code === 200) {
      resourceList.value = response.data;
      loading.value = false
      page.total = resourceList.value.length;
      if (page.total > 500) {
        page.limits.push(page.total);
      }
      dataSource.value = loadDataSource(page.current, page.limit);

      filterCity.value = [...new Set(resourceList.value.map(item => item.city))];
      filterCounty.value = [...new Set(resourceList.value.map(item => item.county))];
      filterTown.value = [...new Set(resourceList.value.map(item => item.town))];
      filterVillage.value = [...new Set(resourceList.value.map(item => item.village))];
    } else {
      layer.msg(response.msg, { icon: 2, time: 2000 });
      return;
    }
  } catch (e) {
    layer.msg(e.message, { icon: 2, time: 3000 });
    return;
  }
}

function filterByValues(data, targetValues, field = null) {
  return data.filter(item =>
    field ? targetValues.some(v => item[field] === v)
      : Object.values(item).some(v => targetValues.includes(v))
  );
}

// 生态分区2自动拼接
watch(
  () => [newResource.ecological_zone, newResource.forest_class],
  ([zoneId, forestId]) => {
    const zoneLabel = ecologicalZoneList.value.find(item => item.id === zoneId)?.name || '';
    const forestLabel = forestClassList.value.find(item => item.id === forestId)?.name || '';
    newResource.ecological_zone_2 = zoneLabel + forestLabel;
  },
)
watch(
  () => [editResource.ecological_zone, editResource.forest_class],
  ([zoneId, forestId]) => {
    const zoneLabel = ecologicalZoneList.value.find(item => item.id === zoneId)?.name || '';
    const forestLabel = forestClassList.value.find(item => item.id === forestId)?.name || '';
    editResource.ecological_zone_2 = zoneLabel + forestLabel;
  },
)

// 监听筛选条件变化
watch(
  () => [filter.city, filter.county, filter.town, filter.forestClass, filter.ecologicalZone],
  ([city, county, town, forestClass, ecologicalZone]) => {
    loading.value = true
    getResourceList().then(() => {
      // 示例1：按字段多值筛选
      if (city.length > 0) {
        resourceList.value = filterByValues(resourceList.value, city, 'city');
        filterCounty.value = [...new Set(resourceList.value.map(item => item.county))];
        filterTown.value = [...new Set(resourceList.value.map(item => item.town))];
        filterVillage.value = [...new Set(resourceList.value.map(item => item.village))];
      }
      if (county.length > 0) {
        resourceList.value = filterByValues(resourceList.value, county, 'county');
        filterTown.value = [...new Set(resourceList.value.map(item => item.town))];
        filterVillage.value = [...new Set(resourceList.value.map(item => item.village))];
      }
      if (town.length > 0) {
        resourceList.value = filterByValues(resourceList.value, town, 'town');
        filterVillage.value = [...new Set(resourceList.value.map(item => item.village))];
      }
      if (forestClass.length > 0) {
        resourceList.value = filterByValues(resourceList.value, forestClass, 'forest_class');
      }
      if (ecologicalZone.length > 0) {
        resourceList.value = filterByValues(resourceList.value, ecologicalZone, 'ecological_zone');
      }
      page.total = resourceList.value.length;
      if (page.limit > 500) {
        page.limits.push(page.total);
      }
      page.current = 1;
      dataSource.value = resourceList.value;
      loading.value = false
    });
  },
)


// // 切换状态
// const changeStatus = (isChecked, row) => {
//   resourceList.value.forEach((item) => {
//     if (item.id === row.id) {
//       layer.msg("Success", { icon: 1 }, () => {
//         item.status = isChecked;
//       })
//     }
//   })
// }

// 删除资源
async function remove() {
  if (selectedKeys.value.length === 0) {
    layer.msg("请选择要删除的资源！", { icon: 2 });
    return;
  } else {
    loading.value = true
    let success_res = []
    let error_res = []
    for (let id of selectedKeys.value) {
      // layer.load(0, { time: 100 })
      await api.get('resource/delete', { id: id }).then((response) => {
        if (response.code === 200) {
          success_res.push(id)
        } else {
          error_res.push(id)
        }
      });

    }
    getResourceList(); // 刷新资源列表
    selectedKeys.value = [];
    loading.value = false
    layer.notify({
      title: "Success",
      content: '成功删除 ' + success_res.length + ' 个资源！\n',
      icon: 1,
      time: 5000,
      offset: 'lt',
    })
    if (error_res.length) {
      layer.notify({
        title: "Error",
        content: error_res.length + ' 个资源删除失败！\n',
        icon: 2,
        time: 5000,
      })
    }
  }
}

// 分页、排序、筛选等参数
const change = (page) => {
  loading.value = true;
  setTimeout(() => {
    dataSource.value = loadDataSource(page.current, page.limit);
    loading.value = false;
  }, 100);
}

// 加载分页数据
const loadDataSource = (page, pageSize) => {
  var response = [];
  var startIndex = ((page - 1) * pageSize);
  var endIndex = page * pageSize;
  response = resourceList.value.slice(startIndex, endIndex);
  return response;
}

onMounted(() => {
  getResourceList();
  getList();
});

</script>
